#include <QTcpServer>
#include <QTcpSocket>
#include <QCoreApplication>
#include <QHostAddress>

class MyServer : public QTcpServer
{

public:
    explicit MyServer(QObject *parent = nullptr) : QTcpServer(parent) {}

protected slots:
    void incomingConnection(qintptr socketDescriptor)
    {
        // 每当有新连接请求时，这个槽函数会被调用
        QTcpSocket *clientSocket = new QTcpSocket(this);
        if (clientSocket->setSocketDescriptor(socketDescriptor)) {
            connect(clientSocket, &QTcpSocket::readyRead, this, &MyServer::readData);
            connect(clientSocket, &QTcpSocket::disconnected, this, &MyServer::socketDisconnected);

            qDebug() << "New connection established: " << clientSocket->peerAddress().toString();
        } else {
            delete clientSocket;
        }
    }

private slots:
    void readData()
    {
        QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
        if (clientSocket) {
            while (clientSocket->bytesAvailable()) {
                QByteArray data = clientSocket->readAll();
                qDebug() << "Received data: " << data;
                // 这里可以添加处理数据的逻辑
            }
        }
    }

    void socketDisconnected()
    {
        QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
        if (clientSocket) {
            qDebug() << "Connection closed: " << clientSocket->peerAddress().toString();
            clientSocket->deleteLater();
        }
    }

};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;
    if (!server.listen(QHostAddress::Any, 8080)) { // 监听所有IP的8080端口
        qDebug() << "Server could not start: " << server.errorString();
        return -1;
    }

    qDebug() << "Server is listening on port " << server.serverPort();

    return a.exec();
}